use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time;
use std::io::{self, Read, Write, BufReader, BufRead};

/*网络*/

//服务端
pub struct Server{
    port: u16,
    client_thread_handle_vec: Vec<thread::JoinHandle<()>>,
}
impl Server {
    //构造
    pub fn new(port: u16) -> Server {
        Server{port, client_thread_handle_vec: Vec::new()}
    }
    //启动
    pub fn start(&mut self){
        let address = format!("127.0.0.1:{}", self.port);
        let listener = TcpListener::bind(address).expect("bind失败");
        for stream in  listener.incoming() {
            let s = stream.expect("获取stream失败");
            //开启线程
            let handle = thread::spawn(move || {
                handle_client(s);
            });
            //保存线程
            self.client_thread_handle_vec.push(handle);
        }
    }
}

//处理客户端
fn handle_client(mut stream: TcpStream) {
    //缓冲区
    let mut buf:[u8; 512] = [0; 512];
    //读取数据
    loop {
        let r = stream.read(&mut buf);
        match r {
            Ok(bytes_read) => {
                if  bytes_read > 0{
                    let s = String::from_utf8_lossy(&buf);
                    println!("{}", s);
                    //写回去
                    stream.write(&buf[..bytes_read]);
                }else {
                    println!("客户端断开连接");
                    break;
                }
            },
            Err(e) => {
                println!("客户端异常断开");
                break;
            }
        }

    }

}

//启动服务端
pub fn start_server(){
    let mut server = Server::new(8082);
    server.start();
    for handle in server.client_thread_handle_vec {
        handle.join().unwrap();
    }
}


//启动客户端
pub fn start_client(){
    let mut stream = TcpStream::connect("127.0.0.1:8082").unwrap();
    let mut input = String::new();
    loop {
        input.clear();
        io::stdin().read_line(&mut input).expect("标准输入读取失败");
        if input.contains("quit") {
            break;
        }
        stream.write(input.as_bytes()).expect("写数据失败");

        let mut reader= BufReader::new(&stream);
        let mut buffer: Vec<u8> = Vec::new();
        reader.read_until(b'\n', &mut buffer).expect("读取失败");

        println!("{}", String::from_utf8(buffer).unwrap());
    }
}